# -*- coding: utf-8 -*-
# @FileName :Request.py
# @Time :2024-01-29 13:35
# author: 小燕子
"""封装请求"""
import jsonpath
from requests import request
from string import Template

from thurs_version.Package.database import Sql


# request # 引用
# request() # 调用
class Argument:
    """存储提取的参数数据"""


class Request:
    def __init__(self):
        self.r = request
        self.d = None  # 接收所有的请求数据
        self.respond = None  # 接受所有的响应对象

    def run(self, **kwargs):
        self.d = kwargs
        self.respond = self.r(**self.d)
        return self

    @property  # 将一个类方法 变更为 一个 类属性的调用方式
    def json(self):
        return self.respond.json()

    def argument(self, **kwargs):
        for k, v in kwargs.items():
            data = jsonpath.jsonpath(self.json, v)
            setattr(Argument, k, data[0])
        return self

    def assert_business(self, assert_data):
        for k, v in assert_data.items():
            data = jsonpath.jsonpath(self.json, k)
            assert data[0] == v, f"业务断言失败，实际拿到的数据：{data[0]},预期的数据：{v}"
        print("业务断言成功")
        return self



    def assert_sql(self, assert_data):
        """

        :param expect_value:
        :param assert_data: 数据库断言数据
        :return:
        """
        dql = assert_data["dql"] # 拿到sql查询语句
        dql = Template(dql).substitute(**self.__argument) #{"id":"id的值”} # 替换关键字
        data = Sql().execute(dql).fetchone() # 执行数据库语句，得到查询结果
        expect_data = jsonpath.jsonpath(data, assert_data["sql_jsonpath"])[0] # 得到数据库响应数据
        expect_value = jsonpath.jsonpath(self.json, assert_data["r_jsonpath"])[0]
        assert expect_data == expect_value, f"数据断言失败，实际拿到的数据是{data},预期的数据是{expect_value}"
        print("数据断言成功")
    @property
    def __argument(self):
        argument_dict = dict(Argument.__dict__)
        argument_dict.pop("__module__")
        argument_dict.pop("__doc__")
        argument_dict.pop("__dict__")
        argument_dict.pop("__weakref__")
        return argument_dict


if __name__ == '__main__':
    request_data = {"request": {
        "headers": {
            "content-type": "application/json"
        },
        "params": {
            "s": "api/user/login",
            "application": "app",
            "application_client_type": "weixin"
        },
        "json": {
            "accounts": "Qik1",
            "pwd": "123456",
            "type": "username"
        },

        "method": "post",
        "url": "http://shop-xo.hctestedu.com:80/index.php",
    },

        "assert_data":
            {"$.code": 0, "$.msg": "登录成功", "$.data.username": "Qik1"}
    }
    Request().run(**request_data["request"]).argument(id="$.data.id", username="$.data.username").assert_business(
        request_data["assert_data"])
    # print(Argument.id)
    # print(Argument.username)
    # print(type(Argument.__dict__))
    # print(Argument.__dict__)